package hc.bre.rest.manage

import hc.bre.cmn.BreException
import hc.bre.project.ProjectDefinition
import hc.bre.rest.admin.AuthUtil
import hc.bre.rest.admin.BreAdminService
import hc.bre.rest.admin.BrePermission

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate

@groovy.transform.CompileStatic
@RestController
@RequestMapping("/api")
class ApiController {
	protected static final Logger _log = LoggerFactory.getLogger(ApiController);
	@Autowired
	MainService mainService;
	@Autowired(required=false)
	BreAdminService adminService;

	@PostMapping("/run")
	public Object runRuleDef(@RequestBody Map map){
		String appKey = map.appKey;
		String appSecret = map.appSecret;
		String rpath = map.rpath;
		
		boolean returnCtx = map.returnCtx?true:false;
		Map data = (Map) map.data;

		if(AuthUtil.user() == null) {
			AuthUtil.DEVMODE || adminService.login(appKey, appSecret, false);
		}

		AuthUtil.permit(rpath,BrePermission.run) {
			def result =  mainService.runRuleDef(rpath, data)
			if(returnCtx) {
				return [variable:data,result:result];
			}
			else return result;
		}
	}
	
	@PostMapping("/downloadProj")
	public Object downloadProj(@RequestBody Map map){
		String appKey = map.appKey;
		String appSecret = map.appSecret;
		String rpath = map.rpath;
		
		if(AuthUtil.user() == null) {
			adminService.login(appKey, appSecret, false);
		}
		AuthUtil.permit(rpath,BrePermission.read) {
			return mainService.loadProject(rpath)
		}
	}
	
	@PostMapping("/publishProj")
	public Object publishProj(@RequestBody Map map){
		String appKey = map.appKey;
		String appSecret = map.appSecret;
		Map data = map.data as Map;
		
		if(AuthUtil.user() == null) {
			adminService.login(appKey, appSecret, false);
		}
		
		AuthUtil.permit(data.rpath as String,BrePermission.update) {
			return mainService.publishProj(data)
		}
	}

}
